package org.example.springtrans.controller;

import org.example.springtrans.service.UserService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.jdbc.datasource.DataSourceTransactionManager;
import org.springframework.transaction.TransactionDefinition;
import org.springframework.transaction.TransactionStatus;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

/**
 * 编程式事务
 */
@RequestMapping("/user")
@RestController
public class UserController {
    // jdbc 事务管理器
    @Autowired
    private DataSourceTransactionManager transactionManager;

    // 定义事务属性
    @Autowired
    private TransactionDefinition transactionDefinition;

    @Autowired
    private UserService userService;

    @RequestMapping("register")
    public String register(String username, String password) {
        TransactionStatus status = transactionManager.getTransaction(transactionDefinition);
        // 用户注册
        userService.register(username, password);
        // 提交事务
//        transactionManager.commit(status);
        // 回滚事务
        transactionManager.rollback(status);
        return "注册成功";
    }
}
